<template>
  <FireWork/>
  <el-container>
    <el-header>
      <el-row class="top-bar">
        <el-col :span="6">
          <div class="grid-content"/>
          <a @click="gotoHomePage" style="color: black;cursor: pointer;">
            首页
          </a>
        </el-col>
        <el-col :span="6">
          <div class="grid-content"/>
          <a @click="goToNewsPage" style="color: black;cursor: pointer;">新闻</a>
        </el-col>
        <el-col :span="6">
          <div class="grid-content"/>
          <a @click="goToAddArticlePage" style="color: black;cursor: pointer;">发布文章</a>
        </el-col>
        <el-col :span="6">
          <div class="grid-content"/>
          <Avatar/>
        </el-col>
      </el-row>
    </el-header>
    <el-main>
      <el-row>
        <el-col :span="4"></el-col>
        <el-col :span="16">
          <h1 style="font-weight: bold">{{ article.title }}
            <el-tag v-if="(article.status)===1" type="warning" style="margin-left: 10px">
              草稿
            </el-tag>
          </h1>
          <div style="background-color: #F6F6F6FF;padding: 5px">
            <div>{{ article.updateTime?.substring(0, 10) }} · 阅读量:{{ article.viewCount }} ·
              评论:{{ article.commentCount }} · 点赞数:{{ article.likeCount }}
            </div>
            <div class="flex gap-2" style="margin-top: 20px">文章标签：
              <el-tag
                  v-for="tag in tags"
                  :key="tag"
                  v-if="tags!=null&&tags?.length>0"
                  style="margin-left: 10px"
              >
                {{ tag }}
              </el-tag>
            </div>
          </div>
          <v-md-preview :text="article.content"></v-md-preview>
          <el-divider/>
          <div>
            <div>
              <el-tooltip content="评论" placement="top">
                <el-button class="custom-button" @click="fetchCommentByArticleId">
                  <img src="@/assets/svg/comment-40.svg"/>
                </el-button>
              </el-tooltip>
              <el-tooltip v-if="article.likeArticle" content="取消点赞" placement="top">
                <el-button class="custom-button" style="margin-left: 20px;margin-top: -7px"
                           @click="likeArticle(article.id)">
                  <img v-if="article.likeArticle" src="@/assets/svg/liked-40.svg"/>
                </el-button>
              </el-tooltip>
              <el-tooltip v-if="!article.likeArticle" content="点赞" placement="top">
                <el-button class="custom-button" style="margin-left: 20px;margin-top: -7px"
                           @click="likeArticle(article.id)">
                  <img v-if="!article.likeArticle" src="@/assets/svg/like-40.svg"/>
                </el-button>
              </el-tooltip>
            </div>
            <el-drawer
                title="评论"
                v-model="drawer"
                :with-header="true"
                size="35%"
                @close="drawer = false"
            >
              <!-- 评论编辑框 -->
              <div>
                <el-form
                    style="max-width: 600px;"
                    :model="commentForm"
                    status-icon
                    label-width="auto"
                    class="demo-ruleForm"
                >
                  <el-form-item>
                    <el-input
                        v-model="commentForm.content"
                        placeholder="欢迎参与评论"
                        type="textarea"
                        :rows="4"
                    />
                  </el-form-item>
                  <el-form-item>
                    <div class="comment-button-container">
                      <el-avatar :size="30" :src="userinfo.avatar"/>
                      <span style="margin-left: 10px">{{ userinfo.nickname }}</span>
                      <el-button type="primary" @click="saveComment(null)" style="position: absolute;right: 15px">
                        评论
                      </el-button>
                    </div>
                  </el-form-item>
                </el-form>
                <el-divider/>
              </div>

              <!-- 评论展示 -->
              <div v-for="comment in commentList" :key="comment.id">
                <div @mouseenter="hoveredComment = comment" class="comment-container">
                  <div style="display: flex;align-items: center">
                    <el-avatar :size="30" :src="comment.commentatorAvatar"/>
                    <span style="margin-left: 10px">{{ comment.commentatorName }}</span>
                    <span style="margin-left: 10px">{{ comment.createTime.substring(0, 10) }} </span>
                    <div class="commentStyle" v-if="hoveredComment === comment">
                      <!-- 回复控件，例如按钮或输入框 -->
                      <el-button :size="'small'" @click="toggleReply(comment)">
                        {{ comment.isReplying ? '收起' : '回复' }}
                      </el-button>
                    </div>

                    <div style="margin-left: auto; margin-right: 10px">
                      <el-button class="custom-button" style="margin-left: 20px;margin-top: -4px"
                                 @click="likeComment(comment.id)">
                        <img v-if="comment.likeComment" src="@/assets/svg/liked-16.svg"/>
                        <img v-if="!comment.likeComment" src="@/assets/svg/like-16.svg"/>
                      </el-button>
                      <span style="margin-left: 5px">{{ comment.likeCount }}</span>
                    </div>

                  </div>
                  <span style="margin-left: 40px;margin-top: 20px">{{ comment.content }}</span>
                </div>


                <!-- 回复编辑框 -->
                <div v-if="comment.isReplying" style="margin-left: 40px;margin-top: 15px">
                  <el-form
                      style="max-width: 400px;"
                      :model="commentForm"
                      status-icon
                      label-width="auto"
                      class="demo-ruleForm"
                  >
                    <el-form-item>
                      <el-input
                          v-model="commentContent"
                          placeholder="欢迎参与评论"
                          type="textarea"
                          :rows="4"
                      />
                    </el-form-item>
                    <el-form-item>
                      <el-button type="primary" :size="'small'" @click="saveComment(comment)">
                        回复
                      </el-button>
                    </el-form-item>
                  </el-form>
                  <el-divider/>
                </div>

                <!-- 二级评论 -->
                <div v-if="comment.commentVoList!=null" v-for="subComment in comment.commentVoList" :key="comment.id"
                     style="margin-left: 40px;margin-top: 5px">
                  <div @mouseenter="hoveredComment = subComment" class="comment-container">
                    <div style="display: flex;justify-items: center;align-items: center">
                      <el-avatar :size="30" :src="comment.commentatorAvatar"/>
                      <span style="margin-left: 10px">{{ subComment.commentatorName }}</span><span
                        style="margin-left: 10px">回复</span> <span
                        style="margin-left: 10px">{{ subComment.parentCommentatorName }}</span>
                      <span style="margin-left: 10px">{{ subComment.createTime.substring(0, 10) }} </span>
                      <div class="commentStyle" v-if="hoveredComment === subComment">
                        <!-- 回复控件，例如按钮或输入框 -->
                        <el-button :size="'small'" @click="toggleReply(subComment)">
                          {{ subComment.isReplying ? '收起' : '回复' }}
                        </el-button>
                      </div>
                      <div style="margin-left: auto; margin-right: 10px">
                        <el-button class="custom-button" style="margin-left: 20px;"
                                   @click="likeComment(subComment.id)">
                          <img v-if="subComment.likeComment" src="@/assets/svg/liked-16.svg"/>
                          <img v-if="!subComment.likeComment" src="@/assets/svg/like-16.svg"/>
                        </el-button>
                        <span style="margin-left: 5px">{{ subComment.likeCount }}</span>
                      </div>
                    </div>
                  </div>
                  <span style="margin-left: 40px;margin-top: 20px">
                  {{ subComment.content }}
                </span>
                  <!-- 回复编辑框 -->
                  <div v-if="subComment.isReplying" style="margin-left: 40px;margin-top: 15px">
                    <el-form
                        style="max-width: 400px;"
                        :model="commentForm"
                        status-icon
                        label-width="auto"
                        class="demo-ruleForm"
                    >
                      <el-form-item>
                        <el-input
                            v-model="commentContent"
                            placeholder="欢迎参与评论"
                            type="textarea"
                            :rows="4"
                        />
                      </el-form-item>
                      <el-form-item>
                        <div>
                          <el-button type="primary" :size="'small'" @click="saveComment(subComment)"
                                     style="margin-left: auto">
                            回复
                          </el-button>
                        </div>
                      </el-form-item>
                    </el-form>
                    <el-divider/>
                  </div>
                </div>
                <el-divider style="margin-block: 5px"/>
              </div>
            </el-drawer>
          </div>
        </el-col>
        <el-col :span="4"></el-col>
      </el-row>
    </el-main>
  </el-container>
  <Footer/>
</template>

<script setup>
import {getCurrentInstance, onMounted, reactive, ref} from 'vue'
import {useRoute, useRouter} from 'vue-router'
import {ListArticleById, LikeArticle} from "@/api/member/article.js";
import {ListCommentByArticleId, SaveComment, LikeComment} from "@/api/member/comment.js";
import {useUserinfo} from "@/components/hooks/useUserinfo.js";
import Avatar from '@/components/Avatar/Avatar.vue'
import Footer from "@/components/Footer/Footer.vue";
import FireWork from "@/components/SpecialEffects/FireWork/FireWork.vue";


const router = useRouter()
const route = useRoute()
const {proxy: ctx} = getCurrentInstance()
const {userinfo} = useUserinfo()


/**点赞评论**/
const likeComment = async (id) => {
  try {
    const params = {
      id: id,
      userId: userinfo.value.id
    }
    const {code, msg} = await LikeComment(params);
    if (code === 200) {

    } else {
      ctx.$message.error(msg)
    }
    window.location.reload();
  } catch (error) {
    ctx.$message.error(error)
  }
}


/**点赞文章**/
const likeArticle = async (id) => {
  try {
    const params = {
      id: id,
      userId: userinfo.value.id
    }
    const {code, msg} = await LikeArticle(params);
    if (code === 200) {

    } else {
      ctx.$message.error(msg)
    }
    window.location.reload();
  } catch (error) {
    ctx.$message.error(error)
  }
}


/** 文章评论 **/
let hoveredComment = ref(null)
const drawer = ref(false)
const commentForm = reactive({
  articleId: '',
  parentId: '',
  commentatorId: '',
  type: 0,
  content: '',
})


/** 回复组件 **/
// currentReplyingCommentId用来跟踪当前正在编辑的评论的ID
const currentReplyingCommentId = ref(null)
const toggleReply = (comment) => {
  if (currentReplyingCommentId != null && currentReplyingCommentId.value !== comment.id) {
    // cancelReply(commentList.value.find(c => c.id === currentReplyingCommentId.value))
    commentList.value.forEach(comment => {
      if (comment.id === currentReplyingCommentId.value) {
        // 关闭非当前评论的回复编辑框
        cancelReply(comment);
      }
      //  关闭非当前评论的二级评论回复编辑框
      if (comment.commentVoList) {
        comment.commentVoList.forEach(subComment => {
          if (subComment.id === currentReplyingCommentId.value) {
            cancelReply(subComment);
          }
        })
      }
    });
  }
  currentReplyingCommentId.value = comment.id
  comment.isReplying = !comment.isReplying
}


/** 自动隐藏关闭未收起的回复编辑框 **/
const cancelReply = (comment) => {
  if (comment && currentReplyingCommentId.value === comment.id) {
    comment.isReplying = false
    currentReplyingCommentId.value = null
    commentContent.value=""
  }
}


/** 获取文章评论信息 **/
const commentList = ref([]);
const fetchCommentByArticleId = async () => {
  drawer.value = true
  try {
    const params = {
      articleId: articleId,
      userId: userinfo.value.id
    }
    const {code, data, msg} = await ListCommentByArticleId(params);
    if (code === 200) {
      commentList.value = data.map(comment => {
        const newComment = {
          ...comment, // 使用扩展运算符保留原始评论的所有属性
          isReplying: false, // 添加isReplying属性并设置为false
        }
        if (comment.commentVoList) {
          newComment.commentVoList = comment.commentVoList.map(subComment => ({
            ...subComment,
            isReplying: false, // 给每个 subComment 添加 isReplying 属性并设置为 false
          }));
        }
        return newComment
      });
      console.log("commentList: ", commentList.value)

    } else {
      ctx.$message.error(msg)
    }
  } catch (error) {
    ctx.$message.error(error)
  }
}


/** 加载文章详细数据,新页面打开 **/
const articleId = route.params.id
const article = ref([]);
const tags = ref([])


/** 保存评论 **/
const commentContent = ref("")
const saveComment = async (comment) => {
  try {
    commentForm.articleId = articleId
    commentForm.parentId = comment == null ? -1 : comment.id
    commentForm.commentatorId = userinfo.value.id
    commentForm.type = comment == null ? 0 : 1
    commentForm.content = comment == null ? commentForm.content : commentContent
    // console.log(commentForm)
    const {code, msg} = await SaveComment(commentForm);
    if (code === 200) {
      ctx.$message.success(msg)
    } else {
      ctx.$message.error(msg)
    }
  } catch (error) {
    ctx.$message.error(error)
  }
  setTimeout(() => {
    window.location.reload();
  }, 1500);
}


/** 获取文章详细内容 **/
const fetchArticleById = async () => {
  try {
    const params = {
      id: articleId,
      userId: userinfo.value.id
    }
    const {code, data, msg} = await ListArticleById(params)
    if (code === 200) {
      // console.log("data",data)
      article.value = data
      if (article.value.tags === null || article.value.tags === '') {
        tags.value = null
      } else {
        tags.value = article.value.tags?.split(",")
      }

    } else {
      ctx.$message.error(msg)
      router.push('/home')
    }
  } catch (error) {
    ctx.$message.error(error)
  }
}


// 跳转到主页
const gotoHomePage = () => {
  router.push('/home')
}


// 跳转发布文章页面
const goToAddArticlePage = () => {
  router.push('/goToAddArticlePage')
}


// 跳转新闻页面
const goToNewsPage = () => {
  router.push('/goToNewsPage')
}


onMounted(() => {
  fetchArticleById();
})


</script>

<style scoped>

.custom-button {
  /* 移除背景色和边框 */
  background-color: transparent;
  border: none;

  /* 移除内边距和外边距 */
  padding: 0;
  margin: 0;

  /* 移除文字阴影、边框阴影等 */
  box-shadow: none;

  /* 移除默认的过渡效果（如果有的话） */
  transition: none;

  /* 如果你需要，可以进一步设置 cursor 属性为 pointer，以表明这个元素是可点击的 */
  cursor: pointer;
}


.commentStyle {
  display: none; /* 默认隐藏编辑按钮 */
}

/* 当 光标悬停在评论上悬停，显示其内部的 .commentStyle */
.comment-container:hover .commentStyle {
  display: flex; /* 显示编辑按钮 */
  margin-left: 20px;
}

.top-bar {
  text-align: center;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}


</style>